package com.orange.hdfs.commons;

import java.io.IOException;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hdfs.DistributedFileSystem;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.log4j.Logger;

import com.orange.conf.entity.ConfigEntity;

public class HDFSCommons {

	private static final Logger logger = Logger.getLogger(HDFSCommons.class);

	private static Configuration conf = null;

	static {
		if (conf == null) {
			conf = new Configuration();
			conf.addResource(new Path(ConfigEntity.getCoreSite()));
			conf.addResource(new Path(ConfigEntity.getHdfsSite()));
			Configuration.addDefaultResource(ConfigEntity.getMapredDefault());
			conf.set("fs.hdfs.impl", DistributedFileSystem.class.getName());
			if (ConfigEntity.isIf_kerberos()) {
				conf.set("hadoop.security.authentication", "Kerberos");
				System.setProperty("java.security.krb5.conf", ConfigEntity.getKerbeorsConf());
				UserGroupInformation.setConfiguration(conf);
				try {
					UserGroupInformation.loginUserFromKeytab(ConfigEntity.getKerbeorsUser(), ConfigEntity.getKerbeorskeytab());
					logger.info("登录成功-----");
				} catch (IOException e) {
					logger.info("登录失败-----");
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * 获取hadoop配置
	 * @return
	 */
	public static Configuration getHadoopConf() {
		return conf;
	}

	/**
	 * 获取HDFS文件系统
	 * @return
	 */
	public static FileSystem getHDFileSystem() {
		FileSystem fs = null;
		try {
			fs = FileSystem.get(conf);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return fs;
	}
}
